package cn.rui.config;

import cn.rui.pojo.Permission;
import cn.rui.pojo.Role;
import cn.rui.pojo.User;
import cn.rui.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 徽州大都督
 * @date 2020/8/29
 */
@Component
@Log4j2
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Reference
    private UserService userService;

    /*private static User user;
    static {
        user=new User ();
        user.setUsername ("admin");
        user.setPassword ("123");
        user.setId (1);
    }*/

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户
        log.info ("登陆用户为:" + username);

        User user = userService.findByUsername (username);

        if (user == null) {
            //用户名不存在
            return null;
        }

        if (user.getStation ()==0){
            //账户被禁用
            return null;
        }

        List<GrantedAuthority> authorities = new ArrayList<> ();
        //动态为用户授权
        Set<Role> roles = user.getRoles ();
        for (Role role : roles) {
            //遍历角色集合，为用户授予角色
            authorities.add (new SimpleGrantedAuthority (role.getKeyword ()));
            Set<Permission> permissions = role.getPermissions ();
            //遍历权限集合，为用户授权
            for (Permission permission : permissions) {

                if (permission.getEnable ().equalsIgnoreCase ("1")){  //验证是否启用
                    authorities.add (new SimpleGrantedAuthority (permission.getKeyword ()));
                }
            }
        }

        //由于数据库密码已经加密，这里就不用再加passwordEncoder.encode ()
        org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User (username, user.getPassword (), authorities);
        return userDetails;
    }
}
